import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get, item } from '@/api/provider/miravia_order'
import { limit } from '@/api/store/goods'

// 初始化
const orderStore = store()

// 选中行
orderStore.select = ref([])
orderStore.selectData = []

// 清空
orderStore.selectEmpty = () => {
  orderStore.select.value = []
  orderStore.selectData = []
}

// 分页
orderStore.page = reactive({
  current: 1,
  pageSize: 50,
  total: 0,
  pageSizeOptions: [50, 100],
  loading: false
})

// 查询类型
orderStore.where = reactive({ 
  key: 'number', 
  value: '',
  time: []
})

// 生成查询数据
orderStore.getWhere = () => {
  // 查询方式
  const where = { 
    [orderStore.where.key]: orderStore.where.value, 
    time: orderStore.where.time 
  }
  // 合并数据
  return Object.assign(where, orderStore.getData())
}

orderStore.get = () => {
  orderStore.getData().page = orderStore.page.current
  orderStore.getData().page_size = orderStore.page.pageSize

  return new Promise((resolve, jeject) => {
    orderStore.page.loading = true
    get(orderStore.getWhere()).then(res => {
      const list = res.data.map(item => {
        item.created_time = app.time.load(item.created_time)
        return item
      })
      orderStore.setList(list)
      // 分页
      orderStore.page.current = res.current_page
      orderStore.page.pageSize = res.per_page
      orderStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      orderStore.page.loading = false
    })
  })
}

// 重置请求
orderStore.reset = async (page, size = null) => {
  orderStore.page.current = page
  if(size) {
    orderStore.page.pageSize = size
  }
  
  // 开始加载
  await orderStore.get()
}

// 加载商品  传入订单数组
orderStore.item = async (raw) => {
  // sku和商品对应索引
  const sku = {}
  const items = {}
  const goods = {} 

  // 请求订单商品
  // 循环出订单Number
  const orders = await item(raw.map(data => data.number))
  // 循环订单
  orders.forEach(order => {
    items[order.order_id] = order.order_items
    // 使用对象key的不重复机制，来拿到所有商品的sku
    order.order_items.forEach(item => {
      sku[item.sku] = true
    })
  })

  // 请求sku对应的商品
  const goodsList = await limit({ number_in: Object.keys(sku) })
  // 循环商品
  goodsList.forEach(item => {
    goods[item.number] = item
  })

  // sku关联商品
  orders.forEach(order => {
    order.order_items.forEach(item => {
      item.goods = goods[item.sku]
    })
  })

  return items
}

export default orderStore